<template>
  <div class="app-container">
    <t-form
      :model="queryParams"
      ref="queryRef"
      layout="inline"
      v-show="showSearch"
      class="mb20"
    >
      <t-form-item label="表名称" prop="tableName">
        <t-input
          v-model="queryParams.tableName"
          placeholder="请输入表名称"
          clearable
          style="width: 200px"
          @enter="handleQuery"
        />
      </t-form-item>
      <t-form-item label="表描述" prop="tableComment">
        <t-input
          v-model="queryParams.tableComment"
          placeholder="请输入表描述"
          clearable
          style="width: 200px"
          @enter="handleQuery"
        />
      </t-form-item>
      <t-form-item label="创建时间" style="width: 308px">
        <t-date-range-picker v-model="dateRange" allow-input clearable />
      </t-form-item>
      <t-form-item>
        <t-space>
          <t-button theme="primary" @click="handleQuery">
            搜索
            <template #icon>
              <t-icon name="search" />
            </template>
          </t-button>
          <t-button theme="default" @click="resetQuery">
            重置
            <template #icon>
              <t-icon name="refresh" />
            </template>
          </t-button>
        </t-space>
      </t-form-item>
    </t-form>

    <t-row :gutter="10" class="mb8">
      <t-col :span="1.5">
        <t-button
          theme="primary"
          @click="handleGenTable"
          v-hasPermi="['tool:gen:code']"
          >生成
          <template #icon>
            <t-icon name="download" />
          </template>
        </t-button>
      </t-col>
      <t-col :span="1.5">
        <t-button
          theme="default"
          @click="openImportTable"
          v-hasPermi="['tool:gen:import']"
          >导入
          <template #icon>
            <t-icon name="upload" />
          </template>
        </t-button>
      </t-col>
      <t-col :span="1.5">
        <t-button
          theme="success"
          :disabled="single"
          @click="handleEditTable"
          v-hasPermi="['tool:gen:edit']"
          >修改
          <template #icon>
            <t-icon name="edit" />
          </template>
        </t-button>
      </t-col>
      <t-col :span="1.5">
        <t-button
          theme="danger"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tool:gen:remove']"
          >删除
          <template #icon>
            <t-icon name="delete" />
          </template>
        </t-button>
      </t-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </t-row>

    <t-table
      v-loading="loading"
      :data="tableList"
      row-key="tableId"
      :columns="columns"
      @select-change="handleSelectionChange"
    >
      <template #serial="scope">
        <span>
          {{
            (queryParams.pageNum - 1) * queryParams.pageSize +
            scope.rowIndex +
            1
          }}
        </span>
      </template>
      <template #action="scope">
        <t-tooltip content="预览" placement="top">
          <t-button
            variant="text"
            theme="primary"
            @click="handlePreview(scope.row)"
            v-hasPermi="['tool:gen:preview']"
          >
            <template #icon>
              <t-icon name="browse" />
            </template>
          </t-button>
        </t-tooltip>
        <t-tooltip content="编辑" placement="top">
          <t-button
            variant="text"
            theme="primary"
            @click="handleEditTable(scope.row)"
            v-hasPermi="['tool:gen:edit']"
          >
            <template #icon>
              <t-icon name="edit" />
            </template>
          </t-button>
        </t-tooltip>
        <t-tooltip content="删除" placement="top">
          <t-button
            variant="text"
            theme="primary"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tool:gen:remove']"
          >
            <template #icon>
              <t-icon name="delete" />
            </template>
          </t-button>
        </t-tooltip>
        <t-tooltip content="同步" placement="top">
          <t-button
            variant="text"
            theme="primary"
            @click="handleSynchDb(scope.row)"
            v-hasPermi="['tool:gen:edit']"
          >
            <template #icon>
              <t-icon name="refresh" />
            </template>
          </t-button>
        </t-tooltip>
        <t-tooltip content="生成代码" placement="top">
          <t-button
            variant="text"
            theme="primary"
            @click="handleGenTable(scope.row)"
            v-hasPermi="['tool:gen:code']"
          >
            <template #icon>
              <t-icon name="download" />
            </template>
          </t-button>
        </t-tooltip>
      </template>
    </t-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 预览界面 -->
    <t-dialog
      :title="preview.title"
      v-model:visible="preview.open"
      width="80%"
      top="5vh"
      attach="body"
      class="scrollbar"
    >
      <t-tabs v-model="preview.activeName">
        <t-tab-panel
          v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
          :value="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
        >
          <t-link
            :underline="false"
            v-copyText="value"
            v-copyText:callback="copyTextSuccess"
            style="float: right"
            >复制
            <template #prefix-icon>
              <t-icon name="file-copy" />
            </template>
          </t-link>
          <pre>{{ value }}</pre>
        </t-tab-panel>
      </t-tabs>
    </t-dialog>
    <import-table ref="importRef" @ok="handleQuery" />
  </div>
</template>

<script setup>
import {
  listTable,
  previewTable,
  delTable,
  genCode,
  synchDb,
} from "@/api/tool/gen";
import router from "@/router";
import importTable from "./importTable";

const route = useRoute();
const { proxy } = getCurrentInstance();

const tableList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const tableNames = ref([]);
const dateRange = ref([]);
const uniqueId = ref("");

const columns = ref([
  {
    colKey: "row-select",
    type: "multiple",
    title: "选择",
    width: 55,
    align: "center",
  },
  { colKey: "serial", title: "序号", width: 60, align: "center" },
  { colKey: "tableName", title: "表名称", ellipsis: true, align: "center" },
  { colKey: "tableComment", title: "表描述", ellipsis: true, align: "center" },
  { colKey: "className", title: "实体", ellipsis: true, align: "center" },
  { colKey: "createTime", title: "创建时间", width: 200, align: "center" },
  { colKey: "updateTime", title: "更新时间", width: 200, align: "center" },
  {
    colKey: "action",
    title: "操作",
    width: 330,
    align: "center",
    fixed: "right",
  },
]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tableName: undefined,
    tableComment: undefined,
  },
  preview: {
    open: false,
    title: "代码预览",
    data: {},
    activeName: "domain.java",
  },
});

const { queryParams, preview } = toRefs(data);

onActivated(() => {
  const time = route.query.t;
  if (time != null && time != uniqueId.value) {
    uniqueId.value = time;
    queryParams.value.pageNum = Number(route.query.pageNum);
    dateRange.value = [];
    proxy.resetForm("queryForm");
    getList();
  }
});

/** 查询表集合 */
function getList() {
  loading.value = true;
  listTable(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      tableList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }
  );
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 生成代码操作 */
function handleGenTable(row) {
  const tbNames = row.tableName || tableNames.value;
  if (tbNames == "") {
    proxy.$modal.msgError("请选择要生成的数据");
    return;
  }
  if (row.genType === "1") {
    genCode(row.tableName).then((response) => {
      proxy.$modal.msgSuccess("成功生成到自定义路径：" + row.genPath);
    });
  } else {
    proxy.$download.zip(
      "/tool/gen/batchGenCode?tables=" + tbNames,
      "ruoyi.zip"
    );
  }
}
/** 同步数据库操作 */
function handleSynchDb(row) {
  const tableName = row.tableName;
  proxy.$modal
    .confirm('确认要强制同步"' + tableName + '"表结构吗？')
    .then(function () {
      return synchDb(tableName);
    })
    .then(() => {
      proxy.$modal.msgSuccess("同步成功");
    })
    .catch(() => {});
}
/** 打开导入表弹窗 */
function openImportTable() {
  proxy.$refs["importRef"].show();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 预览按钮 */
function handlePreview(row) {
  previewTable(row.tableId).then((response) => {
    preview.value.data = response.data;
    preview.value.open = true;
    preview.value.activeName = "domain.java";
  });
}
/** 复制代码成功 */
function copyTextSuccess() {
  proxy.$modal.msgSuccess("复制成功");
}
// 多选框选中数据
function handleSelectionChange(selectedRowKeys, { selectedRowData }) {
  ids.value = selectedRowKeys;
  tableNames.value = selectedRowData.map((item) => item.tableName);
  single.value = selectedRowKeys.length != 1;
  multiple.value = !selectedRowKeys.length;
}
/** 修改按钮操作 */
function handleEditTable(row) {
  const tableId = row.tableId || ids.value[0];
  router.push({
    path: "/tool/gen-edit/index/" + tableId,
    query: { pageNum: queryParams.value.pageNum },
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const tableIds = row.tableId || ids.value;
  proxy.$modal
    .confirm('是否确认删除表编号为"' + tableIds + '"的数据项？')
    .then(function () {
      return delTable(tableIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>
